package organdroid.webview;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends Activity implements OnClickListener {
    private String url = null;
    private WebView webView;
    private EditText et_url;
    private Button btn_login;
    private Button btn_back;
    private Button btn_exit;
    private Button btn_forward;
    private Button btn_menu;
    private Button btn_shou;
    private Button btn_shuqian;
    private SharedPreferences sp;
    private ListView listView;
    private View ll;
    private List<String> strings;
    private ArrayAdapter add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = getSharedPreferences("shuqian", Context.MODE_PRIVATE);
        strings = new ArrayList<>();
// 窗口进度条
        String shuqian = sp.getString("shuqian", null);
        if (!TextUtils.isEmpty(shuqian)){
            String[] shuqians = shuqian.split("shuqian");
            Collections.addAll(strings, shuqians);
        }
        strings.add(0,"本地书签");
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);
        setProgressBarIndeterminate(true);
        ll = findViewById(R.id.ll);
        listView = findViewById(R.id.list);
        add = new ArrayAdapter(this,android.R.layout.simple_list_item_1,strings);
        listView.setAdapter(add);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i==0){
                    return;
                }
                ll.setVisibility(View.VISIBLE);
                listView.setVisibility(View.GONE);
                startReadUrl(strings.get(i));
            }
        });
        webView = findViewById(R.id.webView);
        et_url = findViewById(R.id.et_url);
        btn_login =  findViewById(R.id.btn_login);
        btn_back =  findViewById(R.id.btn_back);
        btn_exit =  findViewById(R.id.btn_exit);
        btn_forward =  findViewById(R.id.btn_forward);
        btn_menu =  findViewById(R.id.btn_menu);
        btn_shou =  findViewById(R.id.btn_shou);
        btn_shuqian =  findViewById(R.id.btn_shuqian);
// 对五个按钮添加点击监听事件
        btn_login.setOnClickListener(this);
        btn_back.setOnClickListener(this);
        btn_exit.setOnClickListener(this);
        btn_forward.setOnClickListener(this);
        btn_menu.setOnClickListener(this);
        btn_shou.setOnClickListener(this);
        btn_shuqian.setOnClickListener(this);
    }

    // btn_login的触发事件 点击后 webView开始读取url
    protected void startReadUrl(String url) {
// TODO Auto-generated method stub
// webView加载web资源
        webView.loadUrl(url);
        et_url.setText(url);
// 覆盖webView默认通过系统或者第三方浏览器打开网页的行为
// 如果为false调用系统或者第三方浏览器打开网页的行为
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
// webView加载web资源
                if (url.substring(0,4).equals("http")){
                    et_url.setText(url);
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }
        });
// 启用支持javascript
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);

        settings.setDomStorageEnabled(true);
// web加载页面优先使用缓存加载
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
// 当打开页面时 显示进度条 页面打开完全时 隐藏进度条
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
// TODO Auto-generated method stub
                setTitle("本页面已加载" + newProgress + "%");
                if (newProgress == 100) {
                    closeProgressBar();
                } else {
                    openProgressBar(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    // 打开进度条
    protected void openProgressBar(int x) {
// TODO Auto-generated method stub
        setProgressBarIndeterminateVisibility(true);
        setProgress(x);
    }

    // 关闭进度条
    protected void closeProgressBar() {
// TODO Auto-generated method stub
        setProgressBarIndeterminateVisibility(false);
    }

    // 改写物理按键 返回键的逻辑
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (listView.isShown()){
                listView.setVisibility(View.GONE);
                ll.setVisibility(View.VISIBLE);
                return true;
            }
            if (webView.canGoBack()) {
// 返回上一页面
                webView.goBack();
                return true;
            } else {
// 退出程序
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    // 对按钮事件的处理
    @Override
    public void onClick(View v) {
// TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_login:
                url = et_url.getText().toString();
                url = url.replace(" ", "");
                startReadUrl(url);
                break;
            case R.id.btn_back:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                break;
            case R.id.btn_forward:
                if (webView.canGoForward()) {
                    webView.goForward();
                }
                break;
            case R.id.btn_exit:
                finish();
                break;
            case R.id.btn_shou:
                if (TextUtils.isEmpty(webView.getUrl())){
                    Toast.makeText(this,"书签不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    strings.add(webView.getUrl());
                    add.notifyDataSetChanged();
                    String shuqian = sp.getString("shuqian", null);
                    if (TextUtils.isEmpty(shuqian)){
                        sp.edit().putString("shuqian", webView.getUrl()).commit();
                    }else {
                        shuqian = shuqian+"shuqian"+webView.getUrl();
                        sp.edit().putString("shuqian", shuqian).commit();
                    }
                    Toast.makeText(this,"书签添加成功",Toast.LENGTH_SHORT).show();

                }

                break;
            case R.id.btn_shuqian:
                ll.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_menu:
                startReadUrl("https://www.baidu.com");
                break;
        }
    }
}